<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/12
 * Time: 9:24
 */
namespace app\common\controller;

use app\common\model\CommissionRebate;
use app\common\model\Orderjd;
use app\common\model\RebateRecord;
use think\Controller;
use think\Db;

class Jd extends Controller {

	//网站ID
	protected $webId = '1587370057';
	
	protected $appkey = 'd8ae799badb94cb6a970b8efe5f41ed6';
	
	protected $secretkey = 'aac86f5f279e40ae9a751bffb5131ecb';
	
	protected $apiUrl = 'https://router.jd.com/api';
	
	public function userPidGet () {
	
	}
	
	
	/**
	 * 订单查询接口
	 * @param $type 查询类型 1下单 2完成
	 * @param $time 查询时间分钟
	 * @param int $page 页数
	 * @return bool
	 */
	public function orderQuery($type, $time, $page = 1) {
		
		$params = $this->getMustParams();
		$params['method'] = "jd.union.open.order.query";
		$postData['orderReq'] = [
			"time" => $time,
			"pageNo" => $page,
			"pageSize" => 500,
			"type" => $type
		];
		$params['param_json'] = json_encode($postData);
		$params['sign'] = $this->getSign($params);
		$res = curlGetInfo($this->apiUrl, 'post', $params);
		return $res;
	}
	
	
	/**
	 * 获取通用推广链接
	 * @param $materialId 推广物料
	 * @param $userId 用户ID
	 * @return bool
	 */
	public function promotionCommonGet ($materialId, $userId) {
		$params = $this->getMustParams();
		$params['method'] = "jd.union.open.promotion.common.get";
		$postData['promotionCodeReq'] = [
			"materialId" => $materialId,
			"siteId" => $this->webId,
			"ext1" => (String) $userId,
		];
		
		
		$params['param_json'] = json_encode($postData);
		$params['sign'] = $this->getSign($params);
		$res = curlGetInfo($this->apiUrl, 'post', $params);
		if(isset($res['jd_union_open_promotion_common_get_response']['result'])) {
			$result = json_decode($res['jd_union_open_promotion_common_get_response']['result'], true);
			if($result['code'] == 200) {
				return $result['data'];
			}
		}
		return false;
	}
	
	/**
	 * 获取必须参数
	 * @return array
	 */
	protected function getMustParams(){
		$data = [
			"timestamp" => date('Y-m-d H:i:s'),
			"v" => "1.0",
			"sign_method" => "md5",
			"format" => "json",
			"method" => "",
			"param_json" => "",
			"access_token" => "",
			"app_key" => $this->appkey
		];
		return $data;
	}
	
	/**
	 * 生成签名
	 * @param $data
	 * @return string
	 */
	protected function getSign($data) {
		ksort($data);
		$str = $this->secretkey;
		foreach ($data as $k => $v) {
			if($v) {
				$str .= $k .$v;
			}
		}
		
		$str .= $this->secretkey;
		$sign = strtoupper(md5($str));
		return $sign;
	}
	
	/**
	 * 操作京东订单
	 * @param $resData
	 * @return string
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function operateOrder($resData) {
		$str = '';
		$orders = [];
		foreach($resData as $order) {
			$orderData = $order;
			unset($orderData['skuList']);
			foreach($order['skuList'] as $sku) {
				$orders[] = array_merge($sku, $orderData);
			}
		}
		
		$insertData = [];
		$model = new Orderjd();
		foreach($orders as $order) {
			$where = [
				'orderId' => $order['orderId'],
				'skuId' => $order['skuId']
			];
			
			$row = $model->where($where)->find();
			if($row) {
				//状态不变，直接跳过
				if($row['validCode'] == $order['validCode']) {
					$str .= $row['id']."订单不变\r\n";
					continue;
				}
				
				switch ($order['validCode']) {
					case $model::ORDER_STATUS_15:
						$order['status'] = $model::STATUS_P;
						break;
					case $model::ORDER_STATUS_16:
						$order['status'] = $model::STATUS_W;
						break;
					case $model::ORDER_STATUS_17:
						$order['status'] = $model::STATUS_W;
						break;
					case $model::ORDER_STATUS_18:
						$order['status'] = $model::STATUS_R;
						break;
					default:
						$order['status'] = $model::STATUS_C;
				}
				
				$updateRes = $model->save($order, $where);
				if($updateRes) {
					$str .= $row['id']."更新成功\r\n";
				} else {
					$str .= $row['id']."更新出错\r\n";
				}
			} else {
				switch ($order['validCode']) {
					case $model::ORDER_STATUS_15:
						$order['status'] = $model::STATUS_P;
						break;
					case $model::ORDER_STATUS_16:
						$order['status'] = $model::STATUS_W;
						break;
					case $model::ORDER_STATUS_17:
						$order['status'] = $model::STATUS_W;
						break;
					case $model::ORDER_STATUS_18:
						$order['status'] = $model::STATUS_R;
						break;
					default:
						$order['status'] = $model::STATUS_C;
				}
				
				$user = Db::name('user')->where(['id' => $order['ext1']])->find();
				if($user) {
					$order['user_id'] = $user['id'];
				}
				
				$insertData[] = $order;
			}
		}
		
		if($insertData) {
			$config = Db::name('commissionRebate')
				->where(['rebate_type' => CommissionRebate::REBATE_TYPE_JD])
				->find();
			
			
			foreach ($insertData as $order) {
				$rule = isset($config) ?$config : [];
				$res = $this->addRow($order, $rule);
				$str .= $res;
			}
		}
		
		return $str;
	}
	
	public function addRow($order, $rule){
		Db::startTrans();
		try {
			//添加记录
			$res = Db::name('orderJd')->insert($order);
			if(!$res) {
				throw new Exception('添加记录出错');
			}
			
			//如果有设置返利规则，且返利金额大于0，进行返利操作
			if($rule && $order['estimateFee'] > 0) {
				$model = new CommissionRebate();
				$recordRes = $model->addRebateRocord($order['merid'], $order['skuId'], $order['estimateFee'], $order['user_id'],$rule, $order['orderId'], RebateRecord::TYPE_JD, '京东');
				
				if(!$recordRes) {
					throw new Exception('发送奖励出错：'.$model->getError());
				}
			}
			
			$this->commit();
			return '添加成功';
		} catch (Exception $e) {
			return '添加出错:'. $e->getMessage();
		}
	}
	
	
	public function search($page, $keyword = ''){
		$url = 'https://union.jd.com/api/goods/search';
		$cookie = '';
		$postData = [
			"data" => [
				"cat2Id" => null,
				"cat3Id" => null,
				"categoryId" => null,
				"deliveryType" => 0,
				"fromCommissionRatio" => null,
				"fromPrice" => null,
				"hasCoupon" => 0,
				"isCare" => 0,
				"isHot" => null,
				"isPinGou" => 0,
				"isZY" => 0,
				"key" => $keyword,
				"keywordType" => "kt1",
				"lock" => 0,
				"orientationFlag" => 0,
				"searchType" => "st1",
				"sort" => null,
				"sortName" => null,
				"toCommissionRatio" => null,
				"toPrice" => null,
			],
			"pageNo" => $page,
			"pageSize" => 20,
			"searchUUID" => "58a0c4c1f0604e67859c1c41d81a9370",
		];
		
		$res = curlGetInfo($url, 'post', json_encode($postData),30,true,['Content-Type: application/json', 'Cookie:'.$cookie]);
		if(isset($res['status']) && $res['status'] === false) {
			return false;
		}
		$goods = $res['data']['unionGoods'];
		$jdGoods = [];
		
		$rebateModel = new CommissionRebate();
		$config = $rebateModel->where([
			'rebate_type' => $rebateModel::REBATE_TYPE_JD
		])->find();
		
		foreach ($goods as $good){
			$good = $good[0];
			$commissionAmount = 0;
			if($config && $good['wlCommission']) {
				if($config['self_type'] == 1) {
					$commissionAmount = floor($good['wlCommission']*$config['self']*100)/100;
				} else {
					$commissionAmount = $config['self'];
				}
			}
			$jdGoods[] = [
				'commission_amount' => $commissionAmount,
				'commission_rate' => $good['wlCommissionRatio']/100,
				'coupon_after_price' => $good['wlPrice']-$good['couponDiscount'],
				'coupon_amount' => $good['couponDiscount'],
				'coupon_click_url' => isset($good['couponLink'])?$good['couponLink']:'',
				'coupon_info' => $good['couponDiscount'].'元优惠券',
				'coupon_remain_count' => "",
				'coupon_total_count' => $good['couponRemainCnt'],
				'exchange_tips' => "确定使用优惠券兑换该现金券吗？",
				'goods_id' => $good['skuId'],
				'goods_img' => 'http://img14.360buyimg.com/n1/'.$good['materialUrl'],
				'goods_price' => $good['wlPrice'],
				'goods_title' => $good['skuName'],
				'goods_type' => "jd",
				'item_url' => "http://item.jd.com/".$good['skuId'].'.html',
				'sale_number' => $good['inOrderCount30Days'],
				'shop_title' => $good['shopName'],
				'small_images' => [],
				'user_type' => "1",
				'isPinGou' => $good['isPinGou'],
				'planId' => $good['planId'],
				'requestId' => $good['requestId']
			];
		}
		
		return $jdGoods;
	}
	
	public function createCouponUrl($data){
		$url = 'https://union.jd.com/api/receivecode/getCode';
		$cookie = '__jdu=1550711885061777343480; __jdv=108460702|baidu|-|organic|not set|1550711885567; 3AB9D23F7A4B3C9B=Z3O2TFPG7BELZYFVL36OTN6UKYKKPKYWLEDKYJW3KLV6S4AIXIVFDCF6GRSOKHPP57GWETSLTPL4I7SOCTMOU4J3II; pinId=aDHCMl9EfQuYvE07b-B1Pw; _tp=xH4%2BQ1DEvng3K%2FVWYB7bmQ%3D%3D; _pst=yunliao888; ssid="k9mJVBZhQ5eymMkqxurPfw=="; unick=yunliao888; ceshi3.com=000; login=true; MNoticeIdyunliao888=202; sidebarStatus=1; TrackID=13v4R7v4wvhkAsPj8EowkTb6YN4JVf1yeUlrWDKJmJXr_VgfGySw5yb2MRTP-rojGQCA-lvFwjl4dLvhMjy3RQ_WZwyCzaWtLR8v2v33VUAU; pin=yunliao888; logining=1; thor=1DBDA6468D90E63C4FDC443BAB20DDEA05E0F820BC636C040EDAA925FF5C30841A1CB1DF5C4705205A0780A74ECA7EBCD2E7209797192C45F2C778783DBD829D20E145E0EA3A2CD210541041F83DF9E3F81CB0219BDBF92521732029232C8B2D27DFD8A9BC6EF0B9D7E63407C6B0EAE1515FD9DF3838CFE37DE42EC6950D326349D63FF3951189618F39378C9589B2F4; RT=""; __jda=209449046.1550711885061777343480.1550711885.1551420948.1551425103.19; __jdb=209449046.19.1550711885061777343480|19.1551425103; __jdc=209449046';
		
		$postData = [
			"data" => [
				"couponLink" => $data['coupon_click_url'],
				"isPinGou" => $data['isPinGou'],
				"isSmartGraphics" => 0,
				"materialId" => $data['goods_id'],
				"materialType" => 1,
				"needAutoVerifyPlan" => [],
				"planId" => $data['planId'],
				"promotionId" => 1715593489,
				"promotionType" => 1,
				"promotionTypeId" => 1587370057,
				"receiveType" => "cps",
				"requestId" => $data['requestId'],
				"wareUrl" => $data['item_url'],
			]
		];
		
		$res = curlGetInfo($url, 'post', json_encode($postData), 30, true, [
			'Content-Type: application/json', 'Cookie:'.$cookie
		]);
		
		
		if (isset($res['data']['data']['couponShortCode'])) {
			return $res['data']['data']['couponShortCode'];
		}
		
		return false;
	}
}